#include "DNSListener.h"
#include<iostream>
#include<arpa/inet.h>
#include<arpa/nameser.h>
#include<netinet/ip.h>
#include<netinet/udp.h>
#include<net/ethernet.h>
#include<resolv.h>
#include<netinet/in.h>
#include<errno.h>

void DNSListener::packetHandler(const u_char* packet, bpf_u_int32 len)
{
	ether_header* ether = (ether_header*)(packet + sizeof(ether_header));
	ip* ipp = (ip*)(packet + this->offset);
	udphdr* udp = (udphdr*)(packet + offset + sizeof(ip));
	HEADER* dns = (HEADER*)(udp + 1);
	u_char* data = (u_char*)(dns + 1);
	if (dns->opcode != QUERY || ntohs(dns->qdcount) != 1 ||
	    dns->ancount || dns->nscount || dns->arcount)
	{
		//response
		return;
	}
	if (dn_expand((u_char*)dns,packet+len,data,ex_name,MAXHOSTNAMELEN) == -1)
	{
		cout << "expand failed: " << strerror(errno) << endl;
		return;
	}
	int datalen = strlen((char*)data);
	if (((int)*(data+datalen+2)) == T_A)
	{
		cout << "Got type A" << endl;
	}
	else
	{
		//not type A
		return;
	}
	//cout << inet_ntoa(ipp->ip_dst) << endl;
	//cout << ex_name << endl;
	dnsres -> writeResponse(ether,ipp,udp,dns,data,ex_name,datalen);
}
